﻿using System;
using System.Collections.Generic;
using Dorm.Helpers;
using Dorm.Maps;
using Dorm.QueryObject;

namespace Dorm.Services
{
    public class PageService
    {
        private static int defaultPageSize;
        public static int DefaultPageSize
        {
            get { return defaultPageSize == 0 ? 20 : defaultPageSize; }
            set { defaultPageSize = value; }
        }

        private DataAccess dataAccess;

        public PageService(DataAccess _dataAccess)
        {
            dataAccess = _dataAccess;
        }

        public List<T> ListPage<T>(Query<T> query, int selectedPage, out long totalRecords)
        {
            return ListPage<T>(query, selectedPage, DefaultPageSize, out totalRecords);
        }

        public List<T> ListPage<T>(Query<T> query, int selectedPage, int pageSize, out long totalRecords)
        {
            int regsToSkip = selectedPage <= 1 ? 0 : (selectedPage - 1) * pageSize;
            string sqlIDsToSkip = "SELECT TOP(" + regsToSkip + ") ID FROM " + typeof (T).Name;

            var pagedQuery = query.Top(pageSize).Filter("ID").NotIn(sqlIDsToSkip);
            var pageList = new FindService(dataAccess).Find(pagedQuery);

            totalRecords = Convert.ToInt64(dataAccess.ExecuteScalar(query.Count().ToString()));

            return pageList;
        }
    }
}
